﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Caching;
using System.Web.Hosting;
using RazorBridge.Helpers;

namespace RazorBridge
{
    /// <summary>
    /// Extend finding Virtual Path and enable to lookup in assembly
    /// </summary>
    class AssemblyResourceProvider : VirtualPathProvider
    {
        public AssemblyResourceProvider() { }

        /// <summary>
        /// Gets a value if path is Resource
        /// </summary>
        /// <param name="virtualPath"> Provide Virtual Path for Application Resource</param>
        /// <returns> Return true if path is Resource; else false</returns>
        private static bool IsAppResourcePath(string virtualPath)
        {
            String checkPath =
               VirtualPathUtility.ToAppRelative(virtualPath);
            return checkPath.StartsWith(string.Format(CultureInfo.InvariantCulture, "{0}{1}", Constants.RELATIVE_PATH_WILD_CARD, Constants.PLUGIN_PATH_WILD_CARD), StringComparison.OrdinalIgnoreCase);
        }

        /// <summary>
        /// Gets a value for Virtual Path existence in file system or resource
        /// </summary>
        /// <param name="virtualPath">Provide Virtual Path to check file system or assembly</param>
        /// <returns>Return true if file exist as file or resources; else false</returns>
        public override bool FileExists(string virtualPath)
        {
            return (IsAppResourcePath(virtualPath) || base.FileExists(virtualPath));
        }

        /// <summary>
        /// Get file from either file system or application resource
        /// </summary>
        /// <param name="virtualPath">Provide virtual path to get file</param>
        /// <returns></returns>
        public override VirtualFile GetFile(string virtualPath)
        {
            if (IsAppResourcePath(virtualPath))
                return new AssemblyResourceVirtualFile(virtualPath);
            else
                return base.GetFile(virtualPath);
        }

        /// <summary>
        /// Get cache dependency for file system virtual path
        /// </summary>
        /// <param name="virtualPath">Provide virtual path</param>
        /// <param name="virtualPathDependencies">Provide virtual path dependency</param>
        /// <param name="utcStart">cache start utc date</param>
        /// <returns>Return cache dependency</returns>
        public override CacheDependency GetCacheDependency(string virtualPath, System.Collections.IEnumerable virtualPathDependencies, DateTime utcStart)
        {
            if (IsAppResourcePath(virtualPath))
                return null;
            else
                return base.GetCacheDependency(virtualPath, virtualPathDependencies, utcStart);
        }

    }

    /// <summary>
    /// Extend virtualFile functionality
    /// </summary>
    class AssemblyResourceVirtualFile : VirtualFile
    {
        string path;

        /// <summary>
        /// Get files from application resource
        /// </summary>
        /// <param name="virtualPath">Provide virtual path</param>
        public AssemblyResourceVirtualFile(string virtualPath)
            : base(virtualPath)
        {
            path = VirtualPathUtility.ToAppRelative(virtualPath);
        }

        /// <summary>
        /// Open files from assembly as stream
        /// </summary>
        /// <returns>Return stream if file found in resource; else NULL</returns>
        public override Stream Open()
        {
            string[] parts = FrameworkUtility.SplitString(path, Convert.ToChar(Constants.PATH_SEPARATOR, CultureInfo.InvariantCulture));
            if (parts != null && parts.Length == 4)
            {
                Assembly assembly = System.Reflection.Assembly.Load(FrameworkUtility.FormatedAssemblyName(parts[2]));
                if (assembly != null)
                {
                    string resourceKey = parts[3];
                    Stream resourceStream = ResourceCacheProvider.CurrentInstance.TryGetCachedResource(resourceKey);
                    if (resourceStream == null)
                    {                       
                        resourceStream =  assembly.GetManifestResourceStream(resourceKey);
                    }
                    if (resourceStream != null)
                    {
                        ResourceCacheProvider.CurrentInstance.TryCacheResource(resourceKey, resourceStream);
                        return resourceStream;
                    }                    
                }
            }

            return null;
        }

    }
}
